package com.markchu.web.structure.controller;

import com.markchu.common.utils.CookieUtils;
import com.markchu.common.utils.HttpServletUtil;
import com.markchu.common.utils.IPUtils;
import com.markchu.common.vo.MessageInfosVo;
import com.markchu.component.redis.utils.RedisHelper;
import com.markchu.modules.system.domain.User;
import com.markchu.modules.system.service.UserService;
import com.markchu.web.structure.test.TestFileUtil;
import com.markchu.web.structure.vo.UserInfoVo;
import org.apache.commons.lang3.StringUtils;
import org.lionsoul.ip2region.xdb.Searcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

public class BaseController {

    private static final Logger logger = LoggerFactory.getLogger(BaseController.class);


    @Autowired
    private UserService userService;


    public String getLocationByIp(){
        HttpServletRequest request = HttpServletUtil.getRequest();
        String dbPath = TestFileUtil.getPath()+"ip2region.xdb";
        Searcher searcher = null;
        try {
            searcher = Searcher.newWithFileOnly(dbPath);
        } catch (IOException e) {
            System.out.printf("failed to create searcher with `%s`: %s\n", dbPath, e);
            return "上海";
        }
        // 2、查询
        String ip = IPUtils.getIpAddr(request);
        if(StringUtils.isEmpty(ip)){
            return "上海";
        }
        try {
            long sTime = System.nanoTime();
            String region = searcher.search(ip);
            if(!StringUtils.isNotEmpty(region)){
                return "上海";
            }
            String[] regions = region.split("\\|");
            if(regions.length>4){
                return regions[4];
            }
//            long cost = TimeUnit.NANOSECONDS.toMicros((long) (System.nanoTime() - sTime));
//            System.out.printf("{region: %s, ioCount: %d, took: %d μs}\n", region, searcher.getIOCount(), cost);
        } catch (Exception e) {
            System.out.printf("failed to search(%s): %s\n", ip, e);
        }

        // 3、关闭资源
        try {
            searcher.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return "上海";
        // 备注：并发使用，每个线程需要创建一个独立的 searcher 对象单独使用。
    }

    public Long getUserIdBy(){
        User user = getUserInfo();
        if(!Objects.equals(user,null)){
            return user.getId();
        }
        return 0L;
    }



    public User getUserInfo(){
        HttpServletRequest request = HttpServletUtil.getRequest();
        HttpServletResponse response = HttpServletUtil.getResponse();
        String session_code = CookieUtils.getCookieValue(request, MessageInfosVo.SESSION_CODE);
        if(Objects.equals(session_code,null)){
            return null;
        }
        String s_code_value = RedisHelper.get(session_code);
        if(Objects.equals(s_code_value,null)){
            return null;
        }
        Long userId = Long.valueOf(s_code_value);//.set(keyCode,String.valueOf(user.getId()));
        User user = userService.getById(userId);
        if(Objects.equals(user,null)){
            return null;
        }
        return user;
    }

    public Map<Long, UserInfoVo> getUserIdNickNameMap(List<Long> userIds) {
        Map<Long,UserInfoVo> dataMap = new HashMap<>();
        userIds = userIds.stream().distinct().collect(Collectors.toList());
        List<User> userList = userService.getByIds(userIds);
        for(User user : userList){
            UserInfoVo userInfoVo = new UserInfoVo();
            String nickName = StringUtils.isNotEmpty(user.getNickname()) ? user.getNickname() : user.getPhone();//.substring(7,11);
            userInfoVo.setNickName(nickName);
            userInfoVo.setUserThum(user.getPicture());
            dataMap.put(user.getId(),userInfoVo);
        }
        return dataMap;
    }

}
